package com.ruoyi.web.controller.system;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.*;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
@Slf4j
@RestController
@RequestMapping("/system/notification")
public class NotificationController {
    @Value("${notification.security.hosts:127.0.0.1}")
    private List<String> validHosts;

    @Autowired
    private IAliSmsService aliSmsService;

    @Autowired
    private IAliVoiceService aliVoiceService;

    @Autowired
    private IEmailService emailService;

    @Autowired
    private IWXMessageService wxMessageService;

    @Autowired
    private TokenService tokenService;
    
    @Autowired
    private JsonValidatorService jsonValidatorService;

    @Autowired
    private IAsyncDetailService asyncDetailService;

    @PostMapping("/send/sms")
    public AjaxResult sendSms(@RequestBody JSONObject request) {
        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        if (!validHosts.contains(ip)) {
            return AjaxResult.error();
        }
        //参数校验
        AjaxResult ret = jsonValidatorService.validate("/system/notification/send/sms.json", request.toJSONString());
        if (ret != null) {
            return ret;
        }
        String tid = asyncDetailService.createTid("短信通知", request.getLong("companyId"));
        aliSmsService.send(request,tid);
        return AjaxResult.success(tid);
    }

    @PostMapping("/send/voice")
    public AjaxResult sendVoice(@RequestBody JSONObject request) {
        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        if (!validHosts.contains(ip)) {
            return AjaxResult.error();
        }
        //参数校验
        AjaxResult ret = jsonValidatorService.validate("/system/notification/send/voice.json", request.toJSONString());
        if (ret != null) {
            return ret;
        }
        String tid = asyncDetailService.createTid("语音通知", request.getLong("companyId"));
        aliVoiceService.send(request,tid);
        return AjaxResult.success(tid);
    }

    @PostMapping("/send/email")
    public AjaxResult sendEmail(@RequestBody JSONObject request) {
        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        if (!validHosts.contains(ip)) {
            return AjaxResult.error();
        }
        //参数校验
        AjaxResult ret = jsonValidatorService.validate("/system/notification/send/email.json", request.toJSONString());
        if (ret != null) {
            return ret;
        }
        String tid = asyncDetailService.createTid("邮件通知", request.getLong("companyId"));
        emailService.send(tid, request);
        return AjaxResult.success(tid);
    }

    /**
     * 生成微信二维码
     *
     * @return
     */
    @GetMapping("/wechat/create_qr_code")
    public AjaxResult createWeChatQRCode() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String weChatQRCode = wxMessageService.createWeChatQRCode(loginUser.getUser());
        // Header设置文件类型（对于ResponseEntity响应的方式，必须设置文件类型）
        Map<String, String> result = new HashMap<>();
        result.put("weCatQECode", weChatQRCode);
        return AjaxResult.success(result);
    }

    /**
     * 获取用户openId并刷新缓存
     *
     * @return
     */
    @GetMapping("/wechat/sync_open_id")
    public AjaxResult getOpenId() {
        //获取用户信息
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String openId = wxMessageService.getOpenId(loginUser.getUsername());
        if (!StringUtils.isEmpty(openId)) {
            // 更新缓存用户信息
            loginUser.getUser().setOpenId(openId);
            tokenService.setLoginUser(loginUser);
        }
        Map<String, String> result = new HashMap<>();
        result.put("openId", openId);
        return AjaxResult.success(result);
    }

    /**
     * 微信公众号服务器配置回调接口
     *
     * @param signature
     * @param timestamp
     * @param nonce
     * @param echostr
     * @return
     */
    @GetMapping("/wechat/callback")
    public String weChatCallBack(String signature, String timestamp, String nonce, String echostr) {
        log.info("微信公众号校验回调参数1{}，参数2{}，参数3{}，参数4{}", signature, timestamp, nonce, echostr);
        Boolean aBoolean = wxMessageService.checkSign(signature, timestamp, nonce);
        if (aBoolean) {
            return echostr;
        }
        return null;
    }

    @PostMapping("/wechat/callback")
    public void getCallBackParam(HttpServletRequest request, HttpServletResponse response) {
        wxMessageService.getCallBackParam(request);
    }

    /**
     * 推送微信公众号模板消息
     *
     * @param request
     * @return
     */
    @PostMapping("/send/wechat")
    public AjaxResult pushWechat(@RequestBody JSONObject request) {
        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        if (!validHosts.contains(ip)) {
            return AjaxResult.error();
        }
        //参数校验
        AjaxResult ret = jsonValidatorService.validate("/system/notification/send/wechat.json", request.toJSONString());
        if (ret != null) {
            return ret;
        }
        String tid = asyncDetailService.createTid("公众号通知", request.getLong("companyId"));
        wxMessageService.pushTemplateMessage(request,tid);
        return AjaxResult.success(tid);
    }
}
